//
//  LocationTool.m
//  SinaWebo
//
//  Created by wwj on 16/6/22.
//  Copyright © 2016年 亦心. All rights reserved.
//

#import "LocationTool.h"

@interface LocationTool ()<CLLocationManagerDelegate>
@property (copy, nonatomic) SuccessBlock block;
@property (strong, nonatomic) CLLocationManager *manager;
@property (strong, nonatomic) CLGeocoder *geocoder;
@end

@implementation LocationTool

- (CLLocationManager *)manager{
    if ([CLLocationManager locationServicesEnabled]) {
        if (_manager == nil) {
            _manager = [[CLLocationManager alloc] init];
            _manager.delegate = self;
            [_manager requestWhenInUseAuthorization];
            NSDictionary *dict =[[NSBundle mainBundle] infoDictionary];
            if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
                NSString *always = dict[@"NSLocationAlwaysUsageDescription"];
                NSString *whenInUse = dict[@"NSLocationWhenInUseUsageDescription"];
                if (always.length > 0) {
                    [_manager requestAlwaysAuthorization];
                }else if (whenInUse.length > 0){
                    [_manager requestWhenInUseAuthorization];
                }
            }
            
            if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0) {
                NSArray *array = dict[@"UIBackgroundModes"];
                if ([array containsObject:@"location"]) {
                    _manager.allowsBackgroundLocationUpdates = YES;
                }
                
            }
            
        }
    }
    return _manager;
}

- (CLGeocoder *)geocoder{
    if (_geocoder == nil) {
        _geocoder = [[CLGeocoder alloc] init];
    }
    return _geocoder;
}

+ (instancetype)sharedLocation{
    static LocationTool *sharedTool;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedTool = [[LocationTool alloc] init];
    });
    return sharedTool;
}

- (void)location:(SuccessBlock)block{
    _block = block;
    [self.manager startUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    [self.geocoder reverseGeocodeLocation:locations.lastObject completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (self.block) {
            self.block(locations.lastObject.coordinate, placemarks.firstObject);
        }
    }];
    [self.manager stopUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    [self.manager startUpdatingLocation];
}
@end
